package thread.juc.read_write_lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多线程
 * 1 写写  互斥  读写互斥(写一半被读)
 * 2 读读 不需要互斥
 */
public class ReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.set((int) (Math.random() * 101));
            }
        }, "Write").start();

        for (int i = 1; i <= 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readWriteLockDemo.get();
                }
            }, "线程" + i).start();
        }
    }
}

class ReadWriteLockDemo {
    private int numeber = 0;

    private java.util.concurrent.locks.ReadWriteLock lock = new ReentrantReadWriteLock();

    public void get() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " : " + numeber);
        } finally {
            lock.readLock().unlock();
        }
    }

    public void set(int number) {
        lock.writeLock().lock();
        try {
            this.numeber = number;
            System.out.println(Thread.currentThread().getName());
        } finally {
            lock.writeLock().unlock();
        }
    }
}
